﻿/**
* @author Alexander Rindo
* @project Flashview
* @version 0.4
* @function This is the GIF extension to the Image class.
**/

package com.alexrindo.flashview.image 
{
	import flash.display.Bitmap;
	import flash.display.Loader;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.ProgressEvent;
	import flash.geom.Rectangle;
	import flash.net.URLRequest;
	import org.gif.events.FrameEvent;
	import org.gif.events.GIFPlayerEvent;
	import org.gif.frames.GIFFrame;
	import org.gif.player.GIFPlayer;
	
	public class GIFImage extends Image
	{
		private var _GIFImage:GIFPlayer
		private var _GIFLoader:Loader
		private var _GIFBitmap:Bitmap
		private var _GIFRect:Rectangle
		private var _urlReq:URLRequest
		private var _frameLoopSet:Boolean
		private var _currentStaticText:String
		
		public function GIFImage(url:String) 
		{
			_GIFImage = new GIFPlayer()
			super(url)
		}
		
		override public function loadImage(url:String):void 
		{
			_urlReq = new URLRequest(url)

			_GIFLoader = new Loader()
			_GIFLoader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, onGIFProgress)
			_GIFLoader.load(_urlReq)
			
			_GIFImage.addEventListener(GIFPlayerEvent.COMPLETE, onGIFLoaded)
			_GIFImage.addEventListener(FrameEvent.FRAME_RENDERED, onFrame)
			_GIFImage.load(_urlReq)
		}
		
		private function onGIFProgress(e:ProgressEvent)
		{
			_imageSize = Math.round(e.bytesTotal / 102.4) / 10
			dispatchEvent(e)
		}
		
		private function onGIFLoaded(e:GIFPlayerEvent)
		{
			_loaded = true

			_GIFBitmap = Bitmap(e.target)
			_GIFRect = e.rect
			
			_imageHolder.addChild(_GIFImage)
			_imageHolder.alpha = 0 
			_imageHeight = _GIFRect.height
			_imageWidth = _GIFRect.width
			_imageHolder.x = -(imageWidth / 2)
			_imageHolder.y = -(imageHeight / 2)
			addChild(_imageHolder)
			
			dispatchEvent(new Event(IMAGE_LOADED))
		}
		
		private function onFrame(e:Event):void
		{
			dispatchEvent(e)
		}
		
		override public function stopLoad():void 
		{
			_GIFLoader.contentLoaderInfo.removeEventListener(ProgressEvent.PROGRESS, onGIFProgress)
		}
		
		public function get totalFrames():int
		{
			return _GIFImage.totalFrames
		}
		
		public function get currentFrame():int
		{
			return _GIFImage.currentFrame
		}
		
		
		
	}

}